# coding:utf-8
import os

import re
import wmi
import time
import platform
import win32com.client as client


def get_network_flow():
    '''监控window平台下网卡的实时的流量信息
    通过当前总流量和一秒后的总流量的差值，来统计实时的网卡流量信息;
    返回的流量单位是KB
    '''
    # if os == "Windows":
    #     c = wmi.WMI()
    #     for interfacePerTcp in c.Win32_PerfRawData_Tcpip_TCPv4():
    #         sentflow = float(interfacePerTcp.SegmentsSentPersec)  # 已发送的流量
    #         receivedflow = float(interfacePerTcp.SegmentsReceivedPersec)  # 接收的流量
    #         present_flow = sentflow + receivedflow  # 算出当前的总流量
    #
    #     # for interfacePerTcp in c.Win32_PerfRawData_Tcpip_TCPv4():
    #     #     sentflow = float(interfacePerTcp.SegmentsSentPersec)  # 已发送的流量
    #     #     receivedflow = float(interfacePerTcp.SegmentsReceivedPersec)  # 接收的流量
    #     #     per_last_present_flow = sentflow + receivedflow  # 算出1秒后当前的总流量
    #     # present_network_flow = (per_last_present_flow - present_flow) / 1024
    #     # print "当前流量为：{0}KB".format("%.2f" % present_network_flow)
    #     return "%.2f" % present_network_flow
    c = wmi.WMI()
    tcps = c.Win32_PerfRawData_Tcpip_TCPv4()
    sentflow = 0.0
    receiveflow = 0.0
    print len(tcps)
    for i in tcps:
        sentflow += float(i.BytesReceivedPersec) / 1024
        receiveflow += i.SegmentsReceivedPersec / 1024
    print receiveflow, sentflow


def get_network():
    c = wmi.WMI()
    interfaces = c.Win32_PerfRawData_Tcpip_NetworkInterface()
    print len(interfaces)
    rec = send = 0.0
    for t in interfaces:
        print t.Name
        print abs(int(t.BytesReceivedPersec))
        print t.BytesSentPersec
        rec += float(t.BytesReceivedPersec) / 1024 / 1024
        send += float(t.BytesSentPersec) / 1024 / 1024
    print rec, send


def get_networkbyte():
    c = wmi.WMI()
    adapters = c.Win32_PerfRawData_Tcpip_NetworkAdapter()
    print len(adapters)
    rec = send = 0.0
    for a in adapters:
        rec += float(a.BytesReceivedPersec) / 1024 / 1024
        send += float(a.BytesSentPersec) / 1024 / 1024
    print rec, send


if __name__ == "__main__":
    # os = platform.system()
    # send, receive = get_network_flow(os)
    # print "已发送{0}MB,已接收{1}MB".format("%.2f" % send, "%.2f" % receive)

    get_network()
    # get_networkbyte()

    # regobj = re.compile(u"(\d+)%")
    # with os.popen("ping www.baidu.com") as f:
    #     res = f.read()
    #     print res
    #     print regobj.search(res).group(1)



